package hashtable;

import java.util.HashMap;
import java.util.Map;


/**
 * WordPattern
 * https://leetcode-cn.com/problems/word-pattern/
 */
public class WordPattern {

    /**
     * 解法1：
     * @param pattern 一种规律 pattern
     * @param str 字符串
     * @return 是否遵循相同的规律
     */
    public boolean solution01(String pattern, String str) {

         char[] ptnArr = pattern.toCharArray();
         String[] strArr = str.split(" ");
         Map<Character,String> map = new HashMap<>();
         if(ptnArr.length != strArr.length) return false;
         char lastKey = ptnArr[0];
         String lastVal = strArr[0];
         for (int i = 0; i < ptnArr.length; i++) {
             char key = ptnArr[i];
             String val = strArr[i];
             if(null == map.get(key)){
                 map.put(key, val);
             }else if (!val.equals( map.get(key))){
                 return false;
             }
             if(key != lastKey  && lastVal.equals(val)){
                 return false;
             }
         }
        return true;
    }
}